"""
现货数据API路由
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from typing import Optional
from datetime import datetime
from ...models.financial import SpotData, SpotDailyData
from ...tasks.spot_tasks import collect_spot_info_task, collect_spot_daily_task
from ...utils.auth import get_current_user
import logging

router = APIRouter(
    prefix="/spot",
    tags=["现货数据"],
    dependencies=[Depends(get_current_user)]
)

@router.get("/info")
async def get_spot_info(exchange: Optional[str] = None):
    """获取现货合约信息"""
    try:
        query = SpotData.query
        if exchange:
            query = query.filter_by(exchange=exchange)
        spots = query.all()
        return [spot.to_dict() for spot in spots]
    except Exception as e:
        logging.error(f"获取现货合约信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取现货合约信息失败")

@router.post("/collect/info")
async def collect_spot_info(exchange: Optional[str] = None):
    """触发现货合约信息采集任务"""
    try:
        task = collect_spot_info_task.delay(exchange=exchange)
        return JSONResponse(content={"task_id": task.id})
    except Exception as e:
        logging.error(f"触发现货合约信息采集任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="触发采集任务失败")

@router.get("/daily")
async def get_spot_daily(symbol: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None):
    """获取现货日线数据"""
    try:
        query = SpotDailyData.query.filter_by(symbol=symbol)
        if start_date:
            query = query.filter(SpotDailyData.date >= start_date)
        if end_date:
            query = query.filter(SpotDailyData.date <= end_date)
        daily_data = query.order_by(SpotDailyData.date).all()
        return [data.to_dict() for data in daily_data]
    except Exception as e:
        logging.error(f"获取现货日线数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取现货日线数据失败")

@router.post("/collect/daily")
async def collect_spot_daily(symbol: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None):
    """触发现货日线数据采集任务"""
    try:
        task = collect_spot_daily_task.delay(symbol=symbol, start_date=start_date, end_date=end_date)
        return JSONResponse(content={"task_id": task.id})
    except Exception as e:
        logging.error(f"触发现货日线数据采集任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="触发采集任务失败")